// H5广告适配器 - 支持多个第三方广告平台

/**
 * 广告平台枚举
 */
export const AdPlatform = {
  GDT: 'gdt',           // 腾讯广点通
  BAIDU: 'baidu',       // 百度联盟
  BYTEDANCE: 'bytedance', // 字节跳动穿山甲
  GOOGLE: 'google'      // Google AdSense
}

/**
 * H5广告适配器基类
 */
class H5AdAdapter {
  constructor(config) {
    this.config = config
    this.platform = config.platform
    this.isInitialized = false
    this.adInstances = new Map()
  }
  
  /**
   * 初始化广告SDK
   * @returns {Promise}
   */
  async init() {
    throw new Error('子类必须实现init方法')
  }
  
  /**
   * 创建激励视频广告
   * @param {Object} options - 广告配置
   * @returns {Object} 广告实例
   */
  createRewardedVideoAd(options) {
    throw new Error('子类必须实现createRewardedVideoAd方法')
  }
  
  /**
   * 创建Banner广告
   * @param {Object} options - 广告配置
   * @returns {Object} 广告实例
   */
  createBannerAd(options) {
    throw new Error('子类必须实现createBannerAd方法')
  }
  
  /**
   * 销毁广告实例
   * @param {string} adId - 广告ID
   */
  destroyAd(adId) {
    const adInstance = this.adInstances.get(adId)
    if (adInstance && adInstance.destroy) {
      adInstance.destroy()
      this.adInstances.delete(adId)
    }
  }
  
  /**
   * 销毁所有广告
   */
  destroyAll() {
    this.adInstances.forEach((adInstance, adId) => {
      this.destroyAd(adId)
    })
  }
}

/**
 * 腾讯广点通适配器
 */
class GDTAdapter extends H5AdAdapter {
  constructor(config) {
    super(config)
    this.sdkUrl = 'https://qzonestyle.gtimg.cn/qzone/biz/gdt/lib/alloyad/alloyad.js'
  }
  
  async init() {
    if (this.isInitialized) {
      return Promise.resolve()
    }
    
    return new Promise((resolve, reject) => {
      // 检查是否已经加载
      if (window.GDT && window.GDT.Ad) {
        this.isInitialized = true
        resolve()
        return
      }
      
      // 动态加载SDK
      const script = document.createElement('script')
      script.src = this.sdkUrl
      script.async = true
      
      script.onload = () => {
        if (window.GDT && window.GDT.Ad) {
          this.isInitialized = true
          resolve()
        } else {
          reject(new Error('GDT SDK加载失败'))
        }
      }
      
      script.onerror = () => {
        reject(new Error('GDT SDK脚本加载失败'))
      }
      
      document.head.appendChild(script)
    })
  }
  
  createRewardedVideoAd(options) {
    if (!this.isInitialized) {
      throw new Error('GDT SDK未初始化')
    }
    
    const adInstance = new window.GDT.Ad({
      appId: this.config.appId,
      placementId: options.placementId,
      type: 'rewardedVideo'
    })
    
    const adId = `rewarded_${Date.now()}`
    this.adInstances.set(adId, adInstance)
    
    return {
      id: adId,
      instance: adInstance,
      show: () => adInstance.show(),
      destroy: () => this.destroyAd(adId)
    }
  }
  
  createBannerAd(options) {
    if (!this.isInitialized) {
      throw new Error('GDT SDK未初始化')
    }
    
    const adInstance = new window.GDT.Ad({
      appId: this.config.appId,
      placementId: options.placementId,
      type: 'banner',
      container: options.container,
      width: options.width || 320,
      height: options.height || 50
    })
    
    const adId = `banner_${Date.now()}`
    this.adInstances.set(adId, adInstance)
    
    return {
      id: adId,
      instance: adInstance,
      show: () => adInstance.show(),
      hide: () => adInstance.hide(),
      destroy: () => this.destroyAd(adId)
    }
  }
}

/**
 * 百度联盟适配器
 */
class BaiduAdapter extends H5AdAdapter {
  constructor(config) {
    super(config)
    this.sdkUrl = 'https://cpro.baidustatic.com/cpro/ui/c.js'
  }
  
  async init() {
    if (this.isInitialized) {
      return Promise.resolve()
    }
    
    return new Promise((resolve, reject) => {
      // 检查是否已经加载
      if (window.BAIDU && window.BAIDU.union) {
        this.isInitialized = true
        resolve()
        return
      }
      
      // 动态加载SDK
      const script = document.createElement('script')
      script.src = this.sdkUrl
      script.async = true
      
      script.onload = () => {
        // 百度联盟SDK加载后需要初始化
        if (window.BAIDU && window.BAIDU.union) {
          window.BAIDU.union.init({
            appId: this.config.appId
          })
          this.isInitialized = true
          resolve()
        } else {
          reject(new Error('百度联盟SDK加载失败'))
        }
      }
      
      script.onerror = () => {
        reject(new Error('百度联盟SDK脚本加载失败'))
      }
      
      document.head.appendChild(script)
    })
  }
  
  createRewardedVideoAd(options) {
    if (!this.isInitialized) {
      throw new Error('百度联盟SDK未初始化')
    }
    
    const adInstance = window.BAIDU.union.createRewardedVideoAd({
      adUnitId: options.placementId
    })
    
    const adId = `rewarded_${Date.now()}`
    this.adInstances.set(adId, adInstance)
    
    return {
      id: adId,
      instance: adInstance,
      show: () => adInstance.show(),
      destroy: () => this.destroyAd(adId)
    }
  }
  
  createBannerAd(options) {
    if (!this.isInitialized) {
      throw new Error('百度联盟SDK未初始化')
    }
    
    const adInstance = window.BAIDU.union.createBannerAd({
      adUnitId: options.placementId,
      container: options.container,
      width: options.width || 320,
      height: options.height || 50
    })
    
    const adId = `banner_${Date.now()}`
    this.adInstances.set(adId, adInstance)
    
    return {
      id: adId,
      instance: adInstance,
      show: () => adInstance.show(),
      hide: () => adInstance.hide(),
      destroy: () => this.destroyAd(adId)
    }
  }
}

/**
 * 字节跳动穿山甲适配器
 */
class ByteDanceAdapter extends H5AdAdapter {
  constructor(config) {
    super(config)
    this.sdkUrl = 'https://sf16-fe-tos-sg.i18n.pstatp.com/obj/ad-pattern-sg/renderer/package_sg.js'
  }
  
  async init() {
    if (this.isInitialized) {
      return Promise.resolve()
    }
    
    return new Promise((resolve, reject) => {
      // 检查是否已经加载
      if (window.Pangolin && window.Pangolin.init) {
        this.isInitialized = true
        resolve()
        return
      }
      
      // 动态加载SDK
      const script = document.createElement('script')
      script.src = this.sdkUrl
      script.async = true
      
      script.onload = () => {
        if (window.Pangolin && window.Pangolin.init) {
          window.Pangolin.init({
            appId: this.config.appId
          })
          this.isInitialized = true
          resolve()
        } else {
          reject(new Error('穿山甲SDK加载失败'))
        }
      }
      
      script.onerror = () => {
        reject(new Error('穿山甲SDK脚本加载失败'))
      }
      
      document.head.appendChild(script)
    })
  }
  
  createRewardedVideoAd(options) {
    if (!this.isInitialized) {
      throw new Error('穿山甲SDK未初始化')
    }
    
    const adInstance = window.Pangolin.createRewardedVideoAd({
      adUnitId: options.placementId
    })
    
    const adId = `rewarded_${Date.now()}`
    this.adInstances.set(adId, adInstance)
    
    return {
      id: adId,
      instance: adInstance,
      show: () => adInstance.show(),
      destroy: () => this.destroyAd(adId)
    }
  }
  
  createBannerAd(options) {
    if (!this.isInitialized) {
      throw new Error('穿山甲SDK未初始化')
    }
    
    const adInstance = window.Pangolin.createBannerAd({
      adUnitId: options.placementId,
      container: options.container,
      width: options.width || 320,
      height: options.height || 50
    })
    
    const adId = `banner_${Date.now()}`
    this.adInstances.set(adId, adInstance)
    
    return {
      id: adId,
      instance: adInstance,
      show: () => adInstance.show(),
      hide: () => adInstance.hide(),
      destroy: () => this.destroyAd(adId)
    }
  }
}

/**
 * 广告适配器工厂
 */
export class AdAdapterFactory {
  /**
   * 创建广告适配器
   * @param {string} platform - 广告平台
   * @param {Object} config - 配置信息
   * @returns {H5AdAdapter} 广告适配器实例
   */
  static createAdapter(platform, config) {
    const adapterConfig = { ...config, platform }
    
    switch (platform) {
      case AdPlatform.GDT:
        return new GDTAdapter(adapterConfig)
      case AdPlatform.BAIDU:
        return new BaiduAdapter(adapterConfig)
      case AdPlatform.BYTEDANCE:
        return new ByteDanceAdapter(adapterConfig)
      default:
        throw new Error(`不支持的广告平台: ${platform}`)
    }
  }
  
  /**
   * 获取支持的平台列表
   * @returns {Array} 平台列表
   */
  static getSupportedPlatforms() {
    return Object.values(AdPlatform)
  }
}

export default AdAdapterFactory